﻿using System;
using System.Collections.Generic;
using System.IO;
using Lon.Util;
using System.Text;


namespace Lon.Server
{
    public class CSMConfigFileProvider : DataProcessProvider
    {

        FrontServerNode frontServer = null;

        public CSMConfigFileProvider(FrontServerNode frontServer)
        {
            this.frontServer = frontServer;
        }


        protected override void ProcessCommandPackage(DataFrame pkg)
        {
         
          
         
         
            byte[] dataBuf= DataStoreService.ReadAllConfigFile(DbmHelper.IdToDbm(pkg.DstId));
            DataFrame df = new DataFrame(pkg.SrcId, pkg.DstId, DataDir.StationData, true, false, false, (byte)pkg.MajorDataType,(byte)0, dataBuf);
                           
            this.frontServer.SendMessage(df);
           
        }

       

        protected override void ProcessDataPackage(DataFrame rPkg)
        {
            if (rPkg.MinorDataType != 2) return;
            try
            {
               
                byte[] unZipBuf =  ZipHelper.UnComPression(rPkg.DataBuf, 0, rPkg.DataBuf.Length);
                BinaryReader br = new BinaryReader(new MemoryStream(unZipBuf), Encoding.Default);
                int fileCount = br.ReadInt32();
                for (int i = 0; i < fileCount; i++)
                {
                    MemoryStream file = new MemoryStream();
                    BinaryWriter bw = new BinaryWriter(file,Encoding.Default);
                    int fileNameLen = br.ReadInt32();
                    bw.Write(fileNameLen);
                    string fileName = Encoding.Default.GetString(br.ReadBytes(fileNameLen));
                    bw.Write(fileName);
                    int fileSize = br.ReadInt32();
                    bw.Write(fileSize);
                    UInt32 createTime = br.ReadUInt32();
                    bw.Write(createTime);
                    UInt32 modifyTime = br.ReadUInt32();
                    bw.Write(modifyTime);
                    UInt32 accessTime = br.ReadUInt32();
                    bw.Write(accessTime);
                    if (fileSize > 0)
                    {
                        byte[] fileData = br.ReadBytes(fileSize);
                        bw.Write(fileData);
                        DataStoreService.SaveConfigFile(DbmHelper.IdToDbm(rPkg.SrcId),fileName,createTime,modifyTime,accessTime,file.ToArray());
                    }
                }
                br.Close();
            }
            catch (Exception e)
            {
                
            }
        }

    }
}

